package zhongbo.javaweb.instagram.util;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 说明：
 * <p>
 * 数组操作工具类
 *
 * @author zhongboWork
 * @version 1.0
 * @since 2021-12-17 17:54
 */
@Slf4j
public class ArrayUtil {

    /**
     * 平均分割数组
     * <p>
     * 将数组均匀的连续分割成多等分
     *
     * @param source 原始数组
     * @param div    平分份数
     * @param <T>    泛型
     * @return 平分后的数组
     */
    public static <T> List<List<T>> divAverageList(List<T> source, int div) {
        List<List<T>> dividedList = new ArrayList<>();
        int total = source.size();

        int divMax = total / div + (total % div == 0 ? 0 : 1);
        int divMin = total / div;
        int divMore = total % div;

        int i = 0;
        int j = 0;
        int k = 0;


        List<T> partList = new ArrayList<>(divMax);
        for (; i < total; i++) {
            if (j >= divMore) {
                if (k >= divMin) {
                    j++;
                    k = 0;
                }
            } else if (k >= divMax) {
                j++;
                k = 0;
            }

            if (log.isDebugEnabled()) {
                log.debug("divAverageList(): max={} min={} mo={}; i={} j={} k={}", divMax, divMin, divMore, i, j, k);
            }
            k++;
            if (dividedList.size() <= j) {
                partList = new ArrayList<>(divMax);
                dividedList.add(partList);
            }
            partList.add(source.get(i));

        }
        return dividedList;
    }
}
